﻿@using System.Net.Http.Headers
@using Tool.Models
@using Tool.Services
@using Tool.Utils
@inject IDialogService dialogService
@inject ISnackbar snackbar
@inject CustomerService customerService
@inject EvdService evdService
@inject IJSRuntime JavaScript
@inject LoginService loginService

<MudGrid>
    <MudItem xs="3">
        <MudTextField @bind-Value="EvdNo" Label="报销单号" Variant="Variant.Text" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" />
    </MudItem>

    <MudItem xs="3" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" Disabled="@_processing" OnClick="GetSyncEvds" Variant="Variant.Filled" Color="Color.Primary">
            @if (_processing)
            {
                <MudProgressCircular Class="ms-n1" Indeterminate="true" />
                <MudText Class="ms-2">Processing</MudText>
            }
            else
            {
                <MudText>获取同步信息</MudText>
            }
        </MudButton>
    </MudItem>
    <MudItem xs="2" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" Disabled="@_downloadingEvd" OnClick="DownloadEvds" Variant="Variant.Filled" Color="Color.Primary">
            @if (_downloadingEvd)
            {
                <MudProgressCircular Class="ms-n1" Indeterminate="true" />
                <MudText Class="ms-2">Processing</MudText>
            }
            else
            {
                <MudText>下载Evd文件</MudText>
            }
        </MudButton>
    </MudItem>
    <MudItem xs="2" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" Disabled="@_downloadingPay" OnClick="DownloadPayFiles" Variant="Variant.Filled" Color="Color.Primary">
            @if (_downloadingPay)
            {
                <MudProgressCircular Class="ms-n1" Indeterminate="true" />
                <MudText Class="ms-2">Processing</MudText>
            }
            else
            {
                <MudText>下载Pay文件</MudText>
            }
        </MudButton>
    </MudItem>
    <MudItem xs="2" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" OnClick="ClearResults" Variant="Variant.Filled" Color="Color.Primary">
            <MudText>清空</MudText>
        </MudButton>
    </MudItem>
    <MudItem xs="12">
        <MudTable Items="@_evds" @bind-SelectedItems="_selectedEvds" Dense="true" Hover="true" Bordered="true" Striped="true" MultiSelection="true" CustomHeader="true" CustomFooter="true">
            <ToolBarContent>
                <MudText Typo="Typo.h6">Evd同步记录(总数：@_totalCount)</MudText>
                <MudSpacer />
            </ToolBarContent>
            <HeaderContent>
                <MudTHeadRow Checkable="true">
                    <MudTh>UserCode</MudTh>
                    <MudTh>FileName</MudTh>
                    <MudTh>FileType</MudTh>
                    <MudTh>FileCTime</MudTh>
                    <MudTh>FilePath</MudTh>
                    <MudTh>SyncTime</MudTh>
                    <MudTh>IsDelete</MudTh>
                    <MudTh>Action</MudTh>
                </MudTHeadRow>
            </HeaderContent>
            <RowTemplate>
                <MudTd DataLabel="UserCode">@context.UserCode</MudTd>
                <MudTd DataLabel="FileName">@context.FileName</MudTd>
                <MudTd DataLabel="FileType">@context.FileType</MudTd>
                <MudTd DataLabel="FileCTime">@context.FileCTime</MudTd>
                <MudTd DataLabel="FilePath">@context.FilePath</MudTd>
                <MudTd DataLabel="SyncTime">@context.SyncTime</MudTd>
                <MudTd DataLabel="IsDelete">@context.IsDelete</MudTd>
                <MudTd DataLabel="Action"><MudButton OnClick="() => ShowEvd(context.FilePath)" Variant="Variant.Filled" Color="Color.Info">查看</MudButton></MudTd>
            </RowTemplate>
            <FooterContent>
                <MudTFootRow Checkable="true">
                    <MudTd colspan="5">Selected: @_selectedEvds?.Count</MudTd>
                </MudTFootRow>
            </FooterContent>
            <PagerContent>
                <MudTablePager />
            </PagerContent>
        </MudTable>
    </MudItem>
</MudGrid>
@code {

    private bool _processing = false;
    private bool _downloadingEvd = false;
    private bool _downloadingPay = false;
    private List<SyncEvdDto> _evds = new List<SyncEvdDto>();
    private HashSet<SyncEvdDto> _selectedEvds = new HashSet<SyncEvdDto>();
    private int _totalCount = 0;

    [Parameter]
    public string UserCode { get; set; }
    [Parameter]
    public string GroupName { get; set; }

    [Parameter]
    public string EvdNo { get; set; }
    [Parameter]
    public string SelectedSite { get; set; }
    [Parameter]
    public HttpResponseHeaders ResponseHeaders { get; set; }


    private async Task GetSyncEvds()
    {
        _processing = true;

        try
        {
            if (string.IsNullOrWhiteSpace(EvdNo) || EvdNo.Length < 14)
            {
                await dialogService.ShowMessageBox("错误", "请输入正确的报销单号，长度至少为14位。");
                return;
            }
            var sql = $"select a.file_name,a.file_type, a.file_ctime, a.file_path, a.user_code, a.isdelete, b.create_time as sync_time  from t_file a left join t_file_state b on a.id = b.file_id where a.file_name like '{EvdNo}%'";
            var totalSql = $"select count(1) from t_file where file_name like '{EvdNo}%'";
            if (SelectedSite != "zwy")
            {
                ResponseHeaders = await loginService.Login(SelectedSite);
            }
            _evds = await evdService.GetSyncEvds(sql, SelectedSite, ResponseHeaders, string.Empty);
            _totalCount = await evdService.GetSyncEvdsCount(totalSql, SelectedSite, ResponseHeaders, string.Empty);
        }
        catch (Exception ex)
        {
            snackbar.Add($"发生异常：{ex.Message}", Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }

    private async Task GetGroupName(string finAdmdivCode, string companyCode)
    {
        int tryCount = 2;
        while (tryCount > 0)
        {
            var centerSql = $"select id, user_code, customer_name, company_code, admdiv_code, admdiv_name,group_id from customer_center where admdiv_code = '{finAdmdivCode}' and company_code='{companyCode}'";
            var centerCustomers = await customerService.GetCustomers(centerSql, SelectedSite, ResponseHeaders);

            GroupName = centerCustomers?.FirstOrDefault()?.GroupName;
            if (!string.IsNullOrWhiteSpace(GroupName))
            {
                tryCount = 0;
            }
            else
            {
                if (EvdNo.Length == 25)
                {
                    finAdmdivCode = EvdNo.Substring(2, 6);
                    companyCode = EvdNo.Substring(8, 9);
                    tryCount--;
                }
                else
                {
                    tryCount = 0;
                    snackbar.Add("解析单号失败", Severity.Error);
                }
            }
        }
    }

    private async Task DownloadEvds()
    {
        _downloadingEvd = true;
        try
        {
            foreach (var item in _selectedEvds)
            {
                await DownloadFile(item.FilePath, item.FileName, "evd");
            }
        }
        catch (Exception ex)
        {
            snackbar.Add($"下载文件异常：{ex.Message}", Severity.Error);
        }
        finally
        {
            _downloadingEvd = false;
        }
    }

    private async Task DownloadPayFiles()
    {
        _downloadingPay = true;
        try
        {
            foreach (var item in _selectedEvds)
            {
                await DownloadFile(item.FilePath, item.FileName, "pay");
            }
        }
        catch (Exception ex)
        {
            snackbar.Add($"下载文件异常：{ex.Message}", Severity.Error);
        }
        finally
        {
            _downloadingPay = false;
        }
    }

    private async Task DownloadFile(string fileUrl, string reimNo, string extension)
    {

        // 下载文件
        // 1. 提取 fileId (去掉第一个 '/' 之前的部分)
        string fileId = fileUrl.Substring(fileUrl.IndexOf("/") + 1);

        // 2. 获取当前时间戳 (秒)
        int ts = (int)(DateTimeOffset.UtcNow.ToUnixTimeSeconds());

        // 3. 生成 token
        string token = FileHelper.GetToken(fileId, ts, "SFqdFASTDFS#@!$%^");

        // 4. 构造带参数的 URL
        string queryString = $"token={token}&ts={ts}";
        string fullFileUrl = $"{fileUrl}?{queryString}";

        // 5. 构造完整的下载 URL
        // 注意：原始 Java 代码中 URL 后面有空格，这里已修正
        var completeUrl = $"{FileHelper.GetFileHost(SelectedSite, GroupName)}/{fullFileUrl}";

        byte[] bytes = await HttpUtil.DownloadBytesAsync(completeUrl);
        await JavaScript.InvokeVoidAsync("downloadFileFromBytes", bytes, $"{reimNo}.{extension}", "application/zip");
    }

    private async Task ShowEvd(string evdUrl)
    {
        var options = new DialogOptions
        {
            FullWidth = true,
            MaxWidth = MaxWidth.Medium,
            CloseOnEscapeKey = true
            // FullScreen = true
        };
        await dialogService.ShowAsync<ShowEvdDetails>("查看EVD", new DialogParameters { { "EvdUrl", evdUrl }, { "SelectedSite", SelectedSite } }, options);
    }

    private void ClearResults()
    {
        _selectedEvds.Clear();
        _evds.Clear();
        _totalCount = 0;
    }
}
